#!/bin/sh

LOG_FILE="/tmp/nacos-import.log"
NACOS_URL="http://127.0.0.1:8848/nacos/v2/cs/config"
TIMEOUT=60  # 最大等待时间(秒)

echo "🚀 Nacos V2 Config Importer [$(date)]" | tee "$LOG_FILE"

# 等待API就绪
wait_for_api() {
  echo "⏳ Checking Nacos API..." | tee -a "$LOG_FILE"
  local start_time=$(date +%s)
  
  while :; do
    if curl -sSf "$NACOS_URL?dataId=probe&group=DEFAULT_GROUP" 2>/dev/null | grep -q "config data not exist"; then
      echo "✅ Nacos V2 API is ready" | tee -a "$LOG_FILE"
      return 0
    fi
    
    local current_time=$(date +%s)
    if [ $((current_time - start_time)) -ge $TIMEOUT ]; then
      echo "❌ Timeout waiting for Nacos API" | tee -a "$LOG_FILE"
      return 1
    fi
    
    sleep 2
    echo "⌛ Waiting... ($((current_time - start_time))s elapsed)" | tee -a "$LOG_FILE"
  done
}

# V2 API导入配置
import_config() {
  local file="$1"
  local dataId=$(basename "$file" | sed 's/\.[^.]*$//')  # 去除扩展名
  
  echo "📦 Importing [$dataId]..." | tee -a "$LOG_FILE"
  
  curl -sS -X POST "$NACOS_URL" \
    -F "dataId=$dataId" \
    -F "group=DEFAULT_GROUP" \
    -F "type=yaml" \
    -F "content=<$file" \
    -w "\nHTTP Status: %{http_code}\n" | tee -a "$LOG_FILE"
  
  [ $? -eq 0 ] && echo "✅ Success" | tee -a "$LOG_FILE" || echo "❌ Failed" | tee -a "$LOG_FILE"
}

main() {
  if ! wait_for_api; then
    exit 1
  fi

  # 处理所有YAML文件（兼容带空格文件名）
  find /nacos/init-config/ -type f \( -iname "*.yaml" -o -iname "*.yml" \) -print0 | while IFS= read -r -d '' file; do
    import_config "$file"
  done

  echo "🎉 Import completed at $(date)" | tee -a "$LOG_FILE"
  echo "🔍 View logs: docker exec -it $(hostname) cat $LOG_FILE" | tee -a "$LOG_FILE"
}

main